﻿using System;
using System.IO;
using SassAndCoffee;
using Telerik.Web.Mvc.Infrastructure;
using Telerik.Web.Mvc.UI;

namespace Telerik.Web.Mvc.UI {
    public class SassAndCoffeeGroupBuilder : WebAssetGroupBuilder {
        private readonly WebAssetGroup assetItemGroup;
        private readonly ISimpleFileCompiler compiler;

        public SassAndCoffeeGroupBuilder(WebAssetGroup assetItemGroup, ISimpleFileCompiler compiler)
            : base(assetItemGroup) {
            this.compiler = compiler;
            this.assetItemGroup = assetItemGroup;
        }

        public virtual WebAssetGroupBuilder Add(string value) {
            assetItemGroup.Items.Add(CreateItem(Utility.Compile(value, assetItemGroup.DefaultPath, compiler)));

            return this;
        }

        private WebAsset CreateItem(string source) {
            Guard.IsNotNullOrEmpty(source, "source");

            if(source.IndexOf("://") < 0) {
                source = source.StartsWith("~/", StringComparison.OrdinalIgnoreCase) ? source : Path.Combine(assetItemGroup.DefaultPath, source).Replace("\\", "/");
            }

            return new WebAsset(source);
        }
    }
}